<!--
 * @Description: 插入SVG元素
-->

<template>
  <div class="tool-container">
    <h4 class="title">车位
      <div class="icon-item">
        <img class="icon" :src="svgStr" alt="">
        <el-button type="text" @click="insertSvg">替换</el-button>
      </div>
    </h4>
    <div class="tool-box">
      <div :data-name="item.parkName" class="tool-item" v-for="item in moduleList" :draggable="true"
        @dragend="onDragend(item)" :key="item.id">
        <p>{{ item.parkName }}<span v-if="item.status == 1">⚡</span></p>
      </div>
    </div>
  </div>
</template>

<script>
import { getImgStr, selectFiles } from '../utils/utils';
import select from '../mixins/select';
import { v4 as uuid } from 'uuid';

import powerSvg from "../assets/park/power.svg"
import port from "../assets/park/port.svg"

// 默认属性
const defaultPosition = {
  originX: 'left',
  originY: 'top',
};
export default {
  name: 'ToolBar',
  mixins: [select],
  inject: ['getModules'],
  data() {
    return {
      showModal: false,
      svgStr: port,
    };
  },
  computed: {
    moduleList() {
      let moduleList = this.getModules()
      const alreadyData = this.canvas.c
        .getObjects().filter(v => 'attchData' in v).map(v => v.attchData.id)

      return moduleList.filter(v => !alreadyData.includes(v.id))
    }
  },
  created() {
  },
  methods: {

    onDragend(item) {
      // let svg = port
      // if (Number(item.status) === 1) svg = powerSvg


      this.insertSvgFile(this.svgStr, item);
    },
    // 插入文件元素
    insertSvgFile(svgFile, attchData) {
      this.fabric.loadSVGFromURL(svgFile || this.svgFile, (objects, options) => {
        console.log(objects, 'objects');
        const item = this.fabric.util.groupSVGElements(objects, {
          ...defaultPosition,
          ...options,
          id: uuid(),
          attchData
        });
        this.canvas.c.add(item)
          .renderAll();
      });
    },
    // 插入Svg
    insertSvg() {
      selectFiles({ accept: '.svg', multiple: true }).then((fileList) => {
        Array.from(fileList).forEach((item) => {
          getImgStr(item).then((file) => {
            // console.log(file);
            this.svgStr = file
          });
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.tool-container {
  .tool-box {
    height: 200px;
    overflow-y: scroll;
    display: flex;
    flex-direction: column;
    justify-content: flex-start !important;

    .tool-item {
      width: 100% !important;
      flex: none;
      box-sizing: border-box;
      margin: 0 !important;
      margin-top: 10px !important;
    }
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .icon-item {
    margin-left: 10px;
    display: flex;
    align-items: center;

    .icon {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }
}
</style>
